<template>
  <div class="new-content">
    <div class="zz"></div>
    <div class="cont">
      <div class="cont-logo">
        <img class="logo" :src="logoUrl" :alt="logo" mode="scaleToFill" />
      </div>
      <img :src="bcImg" mode="scaleToFill" class="bg-img" />
      <div class="info">
        <img :src="qrURL2" mode="aspectFit" class="qrURL2" />
        <div>
          <div>
            <div>{{form.shopName}}</div>
            <img
              src="https://akk.028wkf.cn/kdb-weapp-img/img/ptxg.png"
              mode="scaleToFill"
              class="update-shop-name-img"
              @click="updateShopInfoClick('name')"
            />
          </div>
          <p>长按识别或扫描二维码</p>
        </div>
      </div>
      <div class="copy">{{copyShopAdvertising}}</div>
    </div>
    <div class="buttons">
      <div v-if="!isClickDraw">
        <p @click="updateShopInfoClick('advertising')">宣传语</p>
        <p @click="updataShopImg">宣传图片</p>
        <p @click="drawClick">确定</p>
      </div>
      <div v-else>
        <button @click="handleSaveCanvas">保存图片</button>
        <button open-type="share">立即分享</button>
      </div>
    </div>

    <div class="canvasHidden">
      <canvas
        canvas-id="shareImg"
        style="width:300px;height:520px"
        :hidden="canvasHidden"
      ></canvas>
    </div>

    <div class="popup-window" :class="{show:showPopup}">
      <span class="close-icon" @click="handleHide">&times;</span>
      <div v-if="isUpdateShopName" class="popup-wrap">
        <input
          v-model="shopName"
          class="input-block"
          type="text"
          placeholder="最多输入7个字"
          placeholder-class="placeholder-part"
          maxlength="7"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="handleSave">确定</span>
        </div>
      </div>
      <div v-else class="popup-wrap">
        <input
          v-model="shopAdvertising"
          class="input-block"
          type="text"
          placeholder="最多输入30个字"
          maxlength="30"
          placeholder-class="placeholder-part"
        />
        <div class="popup-btn-wrap">
          <span class="cancel-btn" @click="handleHide">取消</span>
          <span class="confirm-btn" @click="handleSave">确定</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { base64ToSrc } from '@/utils'
import {
  FIND_SHOP_BASE_INFO,
  FIND_SHOP_URL,
  UPDATE_SHOP_QR_LOGO,
  UPLOAD_IMAGE,
  UPDATE_SHOP_BASE_INFO,
  NEW_GENERATE_SHOP_URL,
  UPLOAD_IMAGE2
} from '@/api'

export default {
  components: {},
  props: {},
  data () {
    return {
      auth: {},
      qrURL: '',
      shopURL: '',
      generateState: false,

      qrURL2: '',
      logoUrl: '',
      form: {
        shopName: ''
      },
      bcImg:
        'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/bg_shop_qr_code.png',
      showPopup: false,
      isUpdateShopName: false,
      isOver: false,
      shopName: '',
      shopAdvertising: '',
      copyShopAdvertising: '',
      isClickDraw: false,

      canvasHidden: false,
      shareImgPath: '',

      getImgageLogoUrl: '',
      getImgageBcImg: '',
      getImgageQrURL2: ''
    }
  },
  computed: {
    hasQR () {
      return !!this.qrURL
    },
    btnText () {
      if (this.hasQR) {
        return '更换LOGO'
      } else {
        return '生成店铺收款二维码'
      }
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {
    this.init()
    this.getAuth()
    this.findQRCode()
    this.handleHide()
  },
  onShareAppMessage () {
    let params = {
      title: this.form.shopName,
      path: 'pages/mine/shop-config/qr-code-shop/main'
    }
    return params
  },
  methods: {
    updateShopInfoClick (value) {
      const vm = this
      vm.showPopup = true
      if (value === 'name') {
        vm.isUpdateShopName = true
      } else {
        vm.isUpdateShopName = false
      }
    },
    handleSave () {
      const vm = this
      if (vm.isUpdateShopName) {
        if (vm.shopName && vm.shopName.length > 7) {
          vm.$toast('不能为空或超过7个字符')
          return false
        }
        vm.form.shopName = vm.shopName
      } else {
        if (vm.shopAdvertising.length > 30) {
          vm.$toast('不能超过30个字符')
          return false
        }
        vm.copyShopAdvertising = vm.shopAdvertising
      }
      vm.handleHide()
    },
    handleHide () {
      const vm = this
      vm.showPopup = false
      vm.isUpdateShopName = false
      vm.shopName = ''
      vm.shopAdvertising = ''
    },
    updataShopImg () {
      const vm = this
      vm.$loading.show()
      UPLOAD_IMAGE2()
        .then(r => {
          let res = JSON.parse(r.data)
          vm.$loading.close()
          if (res.code === '0') {
            vm.bcImg = res.data.imgPath
            wx.getImageInfo({
              src: vm.bcImg,
              success: function (res) {
                vm.getImgageBcImg = res.path
              }
            })
          } else {
            vm.$toast(res.message)
          }
        })
        .catch(e => {
          vm.$loading.close()
          console.error(e)
        })
    },
    handleSaveCanvas () {
      const vm = this
      if (vm.auth && vm.auth['scope.writePhotosAlbum'] !== false) {
        wx.saveImageToPhotosAlbum({
          filePath: vm.shareImgPath,
          success: function (res) {
            vm.$toast('操作成功')
          },
          fail: function (err) {
            console.error(err)
            vm.getAuth()
          }
        })
      } else {
        wx.openSetting({
          success: function (res) {
            console.info(res)
          },
          fail: function (err) {
            console.error(err)
          }
        })
        vm.$toast('需要授权后才能继续')
      }
    },
    drawClick () {
      const vm = this
      vm.drawImg()
      vm.isClickDraw = true
    },
    drawImg () {
      const vm = this
      let hintText = '长按识别或扫描二维码'
      let width = 300
      let height = 520
      const ctx = wx.createCanvasContext('shareImg')

      ctx.setFillStyle('#666')
      ctx.setFontSize(14)
      ctx.drawImage(vm.getImgageBcImg, 15, 30, 270, 380)

      ctx.save() // 保存当前ctx的状态
      ctx.beginPath()
      ctx.arc(155, 30, 30, 0, 2 * Math.PI) // 画出圆
      ctx.closePath()
      ctx.clip() // 裁剪上面的圆形
      ctx.drawImage(vm.getImgageLogoUrl, 125, 0, 60, 60)
      ctx.restore() // 还原状态

      ctx.drawImage(vm.getImgageQrURL2, 40, 410, 80, 80)
      ctx.fillText(vm.form.shopName, 140, 450)
      ctx.fillText(hintText, 140, 470)

      if (vm.copyShopAdvertising.length > 16) {
        let allLength = vm.copyShopAdvertising.length
        height = height + 14
        ctx.fillText(vm.copyShopAdvertising.slice(0, 16), 40, 500)
        ctx.fillText(vm.copyShopAdvertising.slice(16, allLength), 40, 514)
      } else {
        ctx.fillText(vm.copyShopAdvertising, 40, 500)
      }

      ctx.draw(false, function () {
        wx.showToast({
          title: '分享图片生成中...',
          icon: 'loading',
          duration: 1000
        })

        setTimeout(function () {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: width,
            height: height,
            destWidth: width * 750 / wx.getSystemInfoSync().windowWidth,
            destHeight: height * 750 / wx.getSystemInfoSync().windowWidth,
            // fileType: 'jpg',
            canvasId: 'shareImg',
            success: function (res) {
              vm.shareImgPath = res.tempFilePath
              console.log(vm.shareImgPath)
            }
          })
        }, 1000)
      })
    },
    handleSaveImg () {
      const vm = this
      let url = vm.qrURL
      // if (url.indexOf('https') === -1 && url.indexOf('http') !== -1) {
      //   url = vm.qrURL.replace('http', 'https')
      // }
      // if (url.indexOf('wxfile') !== -1) {
      //   url = url.replace('wxfile', 'http')
      // }

      if (vm.auth && vm.auth['scope.writePhotosAlbum'] !== false) {
        // wx.downloadFile({
        //   url: url,
        //   success: function (res) {
        wx.saveImageToPhotosAlbum({
          filePath: url,
          success: function (res) {
            vm.$toast('操作成功')
          },
          fail: function (err) {
            console.error(err)
            vm.getAuth()
          }
        })
        //   },
        //   fail: function (err) {
        //     console.error(err)
        //   }
        // })
      } else {
        wx.openSetting({
          success: function (res) {
            console.info(res)
          },
          fail: function (err) {
            console.error(err)
          }
        })
        vm.$toast('需要授权后才能继续')
      }
    },

    getAuth () {
      const vm = this
      wx.getSetting({
        success: function (res) {
          vm.auth = res.authSetting
        },
        fail: function (err) {
          console.error(err)
        }
      })
    },
    findQRCode () {
      const vm = this
      vm.qrURL = ''
      // FIND_SHOP_BASE_INFO(vm.$cookie.get('account').shopId))
      FIND_SHOP_BASE_INFO(vm.$cookie.get('account').shopId)
        .then(r => {
          if (r.data.code === '0') {
            let { onlineQrCode, logo } = r.data.data
            vm.qrURL = onlineQrCode
            vm.qrURL2 = onlineQrCode
            vm.form = r.data.data
            if (logo) {
              if (logo.indexOf('https') === -1 && logo.indexOf('http') !== -1) {
                vm.logoUrl = logo.replace('http', 'https')
              } else {
                vm.logoUrl = logo
              }
            } else {
              vm.logoUrl = logo
            }

            wx.getImageInfo({
              src: vm.logoUrl,
              success: function (res) {
                vm.getImgageLogoUrl = res.path
              }
            })

            wx.getImageInfo({
              src: vm.qrURL2,
              success: function (res) {
                vm.getImgageQrURL2 = res.path
              }
            })

            vm.findShopURL() // 生成小链接
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    }, // 拿到店铺logo
    findShopURL () {
      const vm = this
      let params = {
        shopId: vm.$cookie.get('account').shopId,
        isOffline: false
      }
      FIND_SHOP_URL(params)
        .then(r => {
          if (r.data.code === '0') {
            vm.shopURL = r.data.data
            vm.generateState = true
            vm.test()
            if (r.data.data === '无') {
              vm.isFindOneCode()
            }
          } else if (r.data.code === '-1') {
            vm.isFindOneCode()
          } else {
            vm.generateState = false
            vm.test()
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    isFindOneCode () {
      const vm = this
      NEW_GENERATE_SHOP_URL(vm.$cookie.get('account').shopId, false)
        .then(r => {
          if (r.data.code === '0' && r.data.data) {
            vm.shopURL = r.data.data
            vm.test()
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    test () {
      const vm = this
      vm.$loading.show()
      if (vm.logoUrl) {
        wx.downloadFile({
          url: vm.logoUrl,
          success (res) {
            if (res.statusCode === 200) {
              vm.getQRLogo(res.tempFilePath)
            }
            vm.$loading.close()
          },
          fail: function (err) {
            console.error(err)
            vm.$loading.close()
          }
        })
      } else {
        vm.$loading.close()
        vm.$alert('请先前往店铺配置，生成店铺logo').then(r => {
          vm.$router.go(-1)
        })
      }
    },
    getQRLogo (res) {
      const vm = this
      vm.$loading.show()
      wx.uploadFile({
        url: `https://akk.028wkf.cn/gateway/store-platform/qrCode/buildQRCode?url=${
          vm.shopURL
        }`,
        filePath: res,
        name: 'logo',
        header: {
          'Content-Type': 'multipart/form-data',
          Accept: 'application/json',
          Cookie: vm.$cookie.get('my-cookie')
        },
        formData: {
          logo: res
        },
        success: function (re) {
          base64ToSrc('data:image/png;base64,' + JSON.parse(re.data).data)
            .then(r => {
              vm.qrURL = r
            })
            .catch(e => {
              console.error(e)
            })
          vm.$loading.close()
        },
        fail: function (err) {
          console.error(err)
          vm.$loading.close()
        }
      })
    },
    // getLogoFlie (path) {
    //   wx.uploadFile({
    //     url: `https://akk.028wkf.cn/gateway/store-platform/upload-image?picType=NORMAL&catalog=xiaochengxu`,
    //     filePath: path,
    //     name: 'picFile',
    //     header: {
    //       'Content-Type': 'multipart/form-data',
    //       Accept: 'application/json',
    //       Cookie: this.$cookie.get('my-cookie')
    //     },
    //     success: function (res) {
    //       this.getQRLogo(res)
    //     }
    //   })
    // },
    changeLogo () {
      const vm = this
      if (vm.generateState) {
        UPDATE_SHOP_QR_LOGO(vm.shopURL)
          .then(r => {
            let res = JSON.parse(r.data)
            if (res.code === '0') {
              base64ToSrc('data:image/png;base64,' + res.data)
                .then(r => {
                  vm.uploadNewQR(r)
                })
                .catch(e => {
                  console.error(e)
                })
            } else {
              vm.$toast(res.message)
            }
          })
          .catch(e => {
            console.error(e)
          })
      } else {
        vm.$toast('请先去生成店铺小链接')
      }
    },
    uploadNewQR (filePath) {
      const vm = this
      vm.qrURL = ''
      UPLOAD_IMAGE(filePath)
        .then(r => {
          let res = JSON.parse(r.data)
          if (res.code === '0') {
            vm.qrURL = res.data.imgPath
            vm.updateShopInfo()
          } else {
            vm.$toast(res.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    updateShopInfo () {
      const vm = this

      let params = {
        shopId: vm.$cookie.get('account').shopId,
        onlineQrCode: vm.qrURL
      }

      UPDATE_SHOP_BASE_INFO(params)
        .then(r => {
          if (r.data.code === '0' && r.data.data) {
            vm.$toast('操作成功')
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          console.error(e)
        })
    },
    init () {
      const vm = this
      vm.bcImg =
        'https://akk.028wkf.cn/kdb-weapp-img/new-kdb-xcx/img/bg_shop_qr_code.png'
      vm.isClickDraw = false
      vm.copyShopAdvertising = ''

      vm.getImgageLogoUrl = ''
      vm.getImgageBcImg = ''
      vm.getImgageQrURL2 = ''

      wx.getImageInfo({
        src: vm.bcImg,
        success: function (res) {
          vm.getImgageBcImg = res.path
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import 'static/styles/color.scss';
.new-content {
  position: relative;
  .cont {
    width: 80%;
    position: absolute;
    z-index: 4;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background: #fff;
    .cont-logo {
      position: relative;
      > .logo {
        width: 60px;
        height: 60px;
        position: absolute;
        z-index: 5;
        border-radius: 50px;
        top: -30px;
        left: 50%;
        transform: translate(-50%, 0);
      }
    }
    > .bg-img {
      width: 100%;
      height: 300px;
    }
    > .info {
      display: flex;
      align-items: center;
      padding: 8px 0 12px;
      > .qrURL2 {
        width: 70px;
        height: 70px;
        margin: 0 20px 0 15px;
      }
      > div {
        > div {
          display: flex;
          align-items: center;
          > p {
            font-size: 14px;
            color: #000;
          }
          > .update-shop-name-img {
            width: 18px;
            height: 18px;
            margin-left: 5px;
          }
        }
        > p {
          font-size: 13px;
          color: #666;
        }
      }
    }
    > .copy {
      width: 90%;
      margin: auto;
      font-size: 14px;
      color: #666;
      line-height: 24px;
    }
  }
  .zz {
    position: fixed;
    z-index: 2;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background-color: #000000;
    opacity: 0.5;
  }
  .buttons {
    position: fixed;
    bottom: 0;
    z-index: 4;
    width: 100%;
    > div {
      display: flex;
      align-items: center;
      width: 100%;
      font-size: 14px;
      > p {
        width: 33.33%;
        text-align: center;
        line-height: 40px;
        background: #fff;
      }
      p:last-child {
        background: $dark-blue;
        color: #fff;
      }
      > button {
        font-size: 14px;
        width: 50%;
        border: 0 !important;
        border-radius: 0;
        color: $dark-blue;
        text-align: center;
        line-height: 40px;
        background: #fff;
      }
      button:last-child {
        background: $dark-blue;
        color: #fff;
      }
    }
  }
}
.popup-window {
  display: flex;
  justify-content: center;
  align-items: center;
  > .popup-wrap,
  > .qr-wrap {
    background-color: $white;
    width: 280px;
    border-radius: 8px;
    padding: 15px 15px 60px;
    position: relative;
    overflow: hidden;
    > .input-block {
      width: calc(100% - 20px);
      padding: 5px 10px;
      font-size: 15px;
      border: 1px solid $light-gray;
      border-radius: 4px;
    }
    > .popup-btn-wrap {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-top: 1px solid $light-gray;
      > .cancel-btn,
      > .confirm-btn {
        width: 50%;
        height: 40px;
        line-height: 40px;
        font-size: 15px;
        text-align: center;
        background-color: $white;
        &.confirm-btn {
          color: $blue;
          border-left: 1px solid $light-gray;
        }
      }
    }
  }
}

.canvasHidden {
  position: fixed;
  top: 999px;
}
</style>
